package com.cyf.library.thread

import com.cyf.library.util.logi
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

object ThreadManager {

    var NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors()
    var KEEP_ALIVE_TIME = 1L
    var KEEP_ALIVE_TIME_UNIT: TimeUnit = TimeUnit.SECONDS

    var taskQueue: BlockingQueue<Runnable> = LinkedBlockingQueue()

    private val executorService: ThreadPoolExecutor = ThreadPoolExecutor(
        NUMBER_OF_CORES,
        NUMBER_OF_CORES * 2,
        KEEP_ALIVE_TIME,
        KEEP_ALIVE_TIME_UNIT,
        taskQueue,
        DefaultRejectedExecutionHandler()
    )

    /**
     * 打印线程池相关信息
     */
    fun printThreadExecutorInfo() {
        "corePoolSize:$NUMBER_OF_CORES".logi()
        ("maximumPoolSize:" + NUMBER_OF_CORES * 2).logi()
        "keepAliveTime:$KEEP_ALIVE_TIME".logi()
    }

    /**
     * 启动1个线程
     * @param runnable 线程
     * @param name 线程名称
     */
    fun startThread(runnable: Runnable, name: String) {
        val backgroundThreadFactory = BackgroundThreadFactory()
        backgroundThreadFactory.name = name

        executorService.threadFactory = backgroundThreadFactory
        executorService.submit(runnable)
    }

    /**
     * 结束线程池
     * shutdown只是将线程池的状态设置为SHUTWDOWN状态，正在执行的任务会继续执行下去，没有被执行的则中断
     * shutdownNow则是将线程池的状态设置为STOP，正在执行的任务则被停止，没被执行任务的则返回
     */
    fun stopThreadExecutor() {
        executorService.shutdownNow();
    }
}